package cn.anc.aonicardv.module.ui.recorder;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.anc.aonicardv.Constant;
import cn.anc.aonicardv.R;
import cn.anc.aonicardv.R2;
import cn.anc.aonicardv.bean.AlbumBean;
import cn.anc.aonicardv.bean.VideoBean;
import cn.anc.aonicardv.event.AllSelectEvent;
import cn.anc.aonicardv.event.CancelEvent;
import cn.anc.aonicardv.event.DeleteEvent;
import cn.anc.aonicardv.event.EditEnableEvent;
import cn.anc.aonicardv.event.EditEvent;
import cn.anc.aonicardv.event.MoveEvent;
import cn.anc.aonicardv.event.PlayVideoDataEvent;
import cn.anc.aonicardv.event.SelectEvent;
import cn.anc.aonicardv.event.VideoListDataEvent;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnAlbumItemLongClickListener;
import cn.anc.aonicardv.module.adpter.listener.OnCheckedChangeListener;
import cn.anc.aonicardv.module.adpter.recorder.RecorderAlbumAdapter;
import cn.anc.aonicardv.module.adpter.recorder.RecorderVideoAdapter;
import cn.anc.aonicardv.module.adpter.recorder.RecorderVideoListAdapter;
import cn.anc.aonicardv.module.ui.MainActivity;
import cn.anc.aonicardv.module.ui.base.BaseActivity;
import cn.anc.aonicardv.util.ActivityUtils;
import cn.anc.aonicardv.util.DialogUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.aonicardv.util.ViewUtil;
import cn.anc.aonicardv.widget.CommonDecoration;
import cn.anc.aonicardv.widget.CustomDialog;
import cn.anc.aonicardv.widget.RecorderEditPopWindow;
import cn.anc.aonicardv.widget.WarningDialog;
import cn.anc.httpcontrolutil.CarControl;
import cn.anc.httpcontrolutil.cache.CacheManager;

/**
 * Created by yangdai on 2017/5/23.
 */

public class RecorderVideoListActivity extends BaseActivity implements RecorderEditPopWindow.OnEditListener, CarControl.OnCarControlCallback, CarControl.OnHeartBeatCallBack, View.OnClickListener, OnAlbumItemClickListener, OnAlbumItemLongClickListener, CarControl.OnCardvThumbnailCallback, OnCheckedChangeListener {

    @BindView(R2.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R2.id.tv_right_text)
    TextView rightTv;
    @BindView(R2.id.tv_title)
    TextView titleTv;
    @BindView(R2.id.tv_back)
    LinearLayout backTv;
    @BindView(R2.id.tv_left)
    TextView leftTv;
    private int count;
    private RecorderEditPopWindow editPopWindow;
    private Dialog progressDialog;
    private WarningDialog warningDialog;
    private boolean isDestroy;
    private DialogUtils dialogUtils;
    private RecyclerView videoRv;
    private LinearLayout mLlRootData;
    private TextView mTvUp, mTvDowm, mTvPage;
    private View mLayoutNoDataView;
    private int mPage = 1;
    private  RecorderVideoListAdapter mRecorderVideoListAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_recorder_video_list);
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initVariable() {
        dialogUtils = new DialogUtils();
        warningDialog = dialogUtils.getWarningDialog(this);
        editPopWindow = new RecorderEditPopWindow(getWindow().getWindowManager().getDefaultDisplay().getWidth(), ViewPager.LayoutParams.WRAP_CONTENT, this, false);
        editPopWindow.setShareVisible(true);
        mLlRootData = findViewById(R.id.ll_root_data);
        mTvPage = findViewById(R.id.tv_page);
        mTvUp = findViewById(R.id.tv_up);
        mTvUp.setOnClickListener(this);
        mTvDowm = findViewById(R.id.tv_dowm);
        mTvDowm.setOnClickListener(this);
        mLayoutNoDataView = findViewById(R.id.layout_no_data_view);
        videoRv = findViewById(R.id.rv_video);
        videoRv.setLayoutManager(new GridLayoutManager(this, mPageNum/2){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        videoRv.addItemDecoration(new CommonDecoration(this));
        mRecorderVideoListAdapter = new RecorderVideoListAdapter( this);
        mRecorderVideoListAdapter.setOnItemClickListener(this);
        mRecorderVideoListAdapter.setOnItemLongClickListener(this);
        mRecorderVideoListAdapter.setOnCheckedChangeListener(this);
        videoRv.setAdapter(mRecorderVideoListAdapter);

  }

    @Override
    public void setListener() {
        editPopWindow.setOnEditListenr(this);
        warningDialog.okTv.setOnClickListener(this);
    }

    private String mTitleText;
    @Override
    public void initData() {
        mTitleText = getIntent().getStringExtra(Constant.IntentKeyParam.VIDEO_DATE);
        rightTv.setVisibility(View.VISIBLE);
        rightTv.setText(R.string.select);
        titleTv.setVisibility(View.VISIBLE);
        titleTv.setText(mTitleText);
        isDestroy = false;
    }


    private List<VideoBean> mDataList = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(VideoListDataEvent event) {
        mDataList.clear();
        mDataList.addAll(event.bean);
        LogUtil.e("llcTest0217","VideoListDataEvent mDataList:"+mDataList.size());
        AlbumBean.invertOrderList(mDataList);
        for (int i = 0; i < mDataList.size(); i++) {
            mDataList.get(i).setItemPosition(i);
        }
        mPage = 1;
        setMaxPage();
        mTvPage.setText(mPage + "/" + mMaxPage);
        refreshUi();
    }

    private List<VideoBean> mCurrentList = new ArrayList<>();
    private void refreshUi() {
            if (mDataList == null || mDataList.size()==0) {
                ViewUtil.showContentLayout(Constant.LAYOUT_EMPTY, mLayoutNoDataView, videoRv, R.mipmap.video_empty, getResources().getString(R.string.video_empty_hint));
            } else {
                ViewUtil.showContentLayout(Constant.LAYOUT_DATA, mLayoutNoDataView, videoRv);
                mCurrentList.clear();
                mCurrentList.addAll(listSplitOfPage(mDataList));
                mRecorderVideoListAdapter.refreshDataList(mCurrentList);
                loadVideoThumbs();
            }

    }


    private void loadVideoThumbs() {
        if (mCurrentList == null || mCurrentList.isEmpty() || videoRv == null){
            return;
        }
        List<Integer> idxArray = new ArrayList<>();
        for (int i = 0; i < mCurrentList.size(); i++) {
            if (!CacheManager.checkCacheExist(mCurrentList.get(i).getPath())) {
                idxArray.add(i);
            } else  {
                mRecorderVideoListAdapter.notifyItemChanged(i);
            }
        }
        LogUtil.e("llcTest0217","loadVideoThumbs mCurrentList:"+mCurrentList.size()+" idxArray:"+idxArray.size());
        CarControl.doGetVideoThumbnail(mCurrentList, idxArray, this);
    }

    @Override
    public void OnThumbnailGetted(int index) {
        LogUtil.e("llcTest0217","OnThumbnailGetted index:"+index);
        if (index<mCurrentList.size()){
            mRecorderVideoListAdapter.notifyItemChanged(index);
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
        CarControl.setOnHeartBeatCallBack(this);
        if (!CarControl.IsConnected.get()){
            if (null != warningDialog) {
                if (warningDialog.isShowing()) {
                    warningDialog.dismiss();
                }
                if (!warningDialog.isShowing() && !isDestroyed()) {
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }

            }
        }

    }

    @OnClick(R2.id.tv_left)
    public void allSelect() {
        if (!rightTv.getText().toString().equals(getString(R.string.select))) {
            if (leftTv.getText().toString().equals(getString(R.string.all_select))) {
                leftTv.setText(getString(R.string.cancel_all_select));
                for (VideoBean videoBean:mDataList){
                    videoBean.setCheck(true);
                }
                count = getMediaNum();
                editPopWindow.setEnable(true);
            } else {
                count = 0;
                leftTv.setText(getString(R.string.all_select));
                for (VideoBean videoBean:mDataList){
                    videoBean.setCheck(false);
                }
                editPopWindow.setEnable(false);
            }
            refreshUi();
            titleTv.setText(getString(R.string.selected) + count);
        }
    }

    @OnClick(R2.id.tv_back)
    public void back() {
        exit();
    }

    private int getMediaNum() {
            return mDataList == null ? 0 : mDataList.size();
    }

    @OnClick(R2.id.tv_right_text)
    public void select() {
        count = getMediaNum();
        if (count == 0){
            return;
        }
        if (rightTv.getText().toString().equals(getString(R.string.select))) {
            enterEdit();
        } else {
            exitEdit();
        }
    }






    private void enterEdit() {
        rightTv.setText(getString(R.string.exit));
        leftTv.setText(getString(R.string.all_select));
        backTv.setVisibility(View.GONE);
        leftTv.setVisibility(View.VISIBLE);
//        editPopWindow.showAtLocation(rootLayout, Gravity.BOTTOM, 0, 0);
        count = 0;
        titleTv.setText(getString(R.string.selected) + count);
        mRecorderVideoListAdapter.setEditMode(true);
        for (VideoBean videoBean:mDataList){
            videoBean.setCheck(false);
        }
        refreshUi();
    }

    private void exitEdit() {
        rightTv.setText(getString(R.string.select));
        editPopWindow.setEnable(false);
        editPopWindow.setShareEnable(false);
        backTv.setVisibility(View.VISIBLE);
        leftTv.setVisibility(View.GONE);
        titleTv.setText(mTitleText);
        editPopWindow.dismiss();
        count = 0;
        mRecorderVideoListAdapter.setEditMode(false);
        for (VideoBean videoBean:mDataList){
            videoBean.setCheck(false);
        }
        refreshUi();
    }

    @Override
    public void onItemClick(CheckBox selectCb, int position, boolean isEditMode) {
        int clickPosition = (mPage - 1) * 6 + position;
        if (clickPosition>mDataList.size()-1){
            return;
        }
        if (!isEditMode) {
            ActivityUtils.jumpActivityForResult(this, RecorderPlayVideoActivity.class, new String[]{Constant.IntentKeyParam.POSITION, clickPosition + "", Constant.IntentKeyParam.TYPE, cn.anc.aonicardv.module.ui.recorder.RecorderFragment.TYPE_EVENT}, 10001);
            EventBus.getDefault().postSticky(new PlayVideoDataEvent(mDataList));
        } else {
            boolean isCheck =   mDataList.get(clickPosition).isCheck();
            onCheckItem(!isCheck,clickPosition);
        }
    }

    private void onCheckItem(boolean isCheck,int position) {
        mDataList.get(position).setCheck(isCheck);
        if (isCheck) {
            count++;
        } else{
            count--;
        }
        titleTv.setText(getString(R.string.selected) + count);

        if (count > 0) {
            editPopWindow.setEnable(true);
            editPopWindow.setShareEnable(true);
        } else {
            editPopWindow.setEnable(false);
            editPopWindow.setShareEnable(false);
        }
        if (count == getMediaNum())
            leftTv.setText(getString(R.string.cancel_all_select));
        else {
            leftTv.setText(getString(R.string.all_select));
        }
        refreshUi();
    }




    @Override
    public void onItemLongClick(View view, int position, boolean isEditMode) {
        select();
    }

    @Override
    public void onCheckedChange(boolean isSelect, int position) {
      String checkPath =   mCurrentList.get(position).getPath();
      for (int i=0;i<mDataList.size();i++){
          if (mDataList.get(i).getPath().equals(checkPath)){
              mDataList.get(i).setCheck(isSelect);
          }
      }
    }




    @Override
    public void delete() {
        if (count == 0) {
            Toast.makeText(this, getString(R.string.select_hint), Toast.LENGTH_LONG).show();
            return;
        }
        showDeleteDialog();
    }

    @Override
    public void download() {

    }


    private CustomDialog mDeleteDialog, mMoveDialog;

    public void showDeleteDialog() {

        if (mDeleteDialog == null) {
            mDeleteDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.delete_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            EventBus.getDefault().post(new DeleteEvent());
                            exitEdit();
                            dialog.dismiss();

                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            mDeleteDialog.setCancelable(true);
            mDeleteDialog.setCanceledOnTouchOutside(true);
        }
        mDeleteDialog.show();


    }

    public void showMoveDialog() {

        if (mMoveDialog == null) {
            mMoveDialog = new CustomDialog.AlertBuilder(this)
                    .setContentText(getString(R.string.move_hint))
                    .setNegativeBtn(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            isMove = true;
                            EventBus.getDefault().post(new MoveEvent());
                            exitEdit();
                            dialog.dismiss();

                        }
                    })
                    .setPositiveBtn(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).createPromptDialog();
            mMoveDialog.setCancelable(true);
            mMoveDialog.setCanceledOnTouchOutside(true);
        }
        mMoveDialog.show();


    }





    @Override
    public void cancel() {
        exitEdit();
    }

    private boolean isMove = false;


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SelectEvent event) {
        if (event.isSelect) {
            count++;
        } else
            count--;
        titleTv.setText(getString(R.string.selected) + count);
        if (count > 0) {
            editPopWindow.setEnable(true);
            editPopWindow.setShareEnable(true);
        } else {
            editPopWindow.setEnable(false);
            editPopWindow.setShareEnable(false);
        }
        if (count == getMediaNum())
            leftTv.setText(getString(R.string.cancel_all_select));
        else {
            leftTv.setText(getString(R.string.all_select));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EditEnableEvent event) {
        if (event.isEnable)
            rightTv.setEnabled(true);
        else
            rightTv.setEnabled(false);
    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        EventBus.getDefault().removeAllStickyEvents();
        isDestroy = true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (editPopWindow.isShowing())
                exitEdit();
            else {
                exit();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        CarControl.doStopGetThumbnail();
        finish();

    }



    @Override
    public void OnCommandCallback(int code, CarControl.CommandResponseInfo info) {
        LogUtil.e("aoni123", "--退出记录仪相册返回---info-------:" + info.toString());
        if (isDestroy)
            return;
        switch (info.msg_id) {

            default:
                break;
        }
    }

    @Override
    public void OnHeartBeatConnectOK() {
    }

    @Override
    public void OnHeartBeatConnectFail() {
    }
    private Handler mHandler = new Handler();
    @Override
    public void OnHeartBeatDisconnect() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != warningDialog) {
                    warningDialog.setHint(getString(R.string.tip_cardv_disconnect)).show();
                }
            }
        }, 500);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_ok:
                warningDialog.dismiss();
                startActivity(new Intent(this, MainActivity.class));
                break;
            case R.id.tv_up:
                if (mPage > 1 && mMaxPage > 0 && mPage <= mMaxPage) {
                    CarControl.doStopGetThumbnail();
                    mPage--;
                    refreshUi();
                }
                break;
            case R.id.tv_dowm:
                if (mMaxPage > 0 && mPage < mMaxPage) {
                    CarControl.doStopGetThumbnail();
                    mPage++;
                    refreshUi();
                }
                break;
        }

    }


    @Override
    public void share() {
    }


    private int mMaxPage = 0;
    private int mPageNum = 6;
    private void setMaxPage() {
        //获取总页数
        int maxPage = mDataList.size() / mPageNum;
        if (maxPage * mPageNum < mDataList.size()) {
            maxPage++;
        }
        mMaxPage = maxPage;
    }

    private List<VideoBean> listSplitOfPage(List<VideoBean> mList) {
        List<VideoBean> mBeanList = new ArrayList<>();
        if (null == mList || mList.size() == 0 || mPage < 1) {
            mPage = 1;
        } else {
            //获取总页数
            int maxPage = mList.size() / mPageNum;
            if (maxPage * mPageNum < mList.size()) {
                maxPage++;
            }
            mMaxPage = maxPage;
            if (mPage > maxPage) {
                mPage = maxPage;
            }
            mTvPage.setText(mPage + "/" + mMaxPage);
            //通过当前页码获取当前应该显示的数据list
            int index = 0;
            for (int i = 0; i < mPageNum; i++) {
                index = (mPage - 1) * mPageNum + i;
                if (index < mList.size()) {
                    mBeanList.add(mList.get(index));
                } else {
                    break;
                }
            }
        }
        return mBeanList;

    }





}
